var House = House || {};
House = function(camera, scene) {
	this.facilityMoveFlg = false;
	this.camera = camera;
	this.scene = scene;
	this.wallHight = 210;
	this.wallThick = 20;
	this.houseSession = null;
	// {
		// _id:null,								
		// hsid:null,												
		// rooms:{
			// roomId:null,			
			// roomType:null,							
			// position:null,
			// size:null,										
			// facilities:{										
				// rndId:null,				
				// gid:null,
				// position:null,
				// rotation:null,
				// parasitizedFace:{
					// name:null,
					// positionX:0,positionY:0,positionZ:0,
					// sizeX:0,sizeY:0,sizeZ:0,
					// }
				// }
			// }			
	// };
	this.houseGoodsInfo = null;
	this.facility = new FacilityNew;
	this.facility.init(scene, camera);
	this.scene = scene;
	
	this.releaseFacility=function() {
		this.facilityMoveFlg = false;
		if(!this.facility.facMesh) {
			return false;
		}

		// var ihs = -1;
		// for(var j in this.houseSession) {
		// 	if(this.houseSession[j].rndId == this.facility.name) {
		// 		ihs = j;
		// 		break;
		// 	}
		// }
		// 			判断goods在哪个房间
		var rooms = this.houseSession.rooms;
		console.warn(this.houseSession);
		var delJ=-1,delK=-1;
		for(var j in rooms){
		  for(var k in rooms[j].facilities){
          var facilities=rooms[j].facilities[k];
          if(facilities.rndId==this.facility.goodsSession.rndId){
            delK=k;
            delJ=j;
            break;
          }		    
		  }
		  
		}
		
		if(delJ!=-1&&delK!=-1)
		rooms[delJ].facilities.splice(delK,1);
		
		for(var i in rooms) {
			if(Number(rooms[i].position.x) + Number(rooms[i].size.width) / 2 >= this.facility.facMesh.position.x &&  Number(rooms[i].position.x) - Number(rooms[i].size.width) / 2 <= this.facility.facMesh.position.x && Number(rooms[i].position.z) + Number(rooms[i].size.depth) / 2 >= this.facility.facMesh.position.z &&  Number(rooms[i].position.z) - Number(rooms[i].size.depth) / 2 <= this.facility.facMesh.position.z) {
				this.facility.release();
				rooms[i].facilities.push({
					rndId:this.facility.goodsSession.rndId,
					gid : this.facility.goodsSession.gid,
					position : {
						x : this.facility.goodsSession.position.x,
						y : this.facility.goodsSession.position.y,
						z : this.facility.goodsSession.position.z
					},
					rotation : {
						x : this.facility.goodsSession.rotation.x,
						y : this.facility.goodsSession.rotation.y,
						z : this.facility.goodsSession.rotation.z
					},
					parasitizedFace:this.facility.goodsSession.parasitizedFace
				});
				return true;
			}
		}
		return false;
		//this.houseSession.push(roomSession);
	};
	this.getFloorMaterial = function() {

		var texturePainting = null;
		texturePainting = THREE.ImageUtils.loadTexture("images/webgl/grid.png", THREE.UVMapping, THREE.RepeatWrapping, THREE.RepeatWrapping);
		floorTextureMaterial = new THREE.MeshBasicMaterial({
			color : 0xffffff,
			map : texturePainting
		});
		return floorTextureMaterial;
	};
	this.loadHouseStyle = function(id, roomStyles,loadHouse) {
		this.hsid = id;
		if(!loadHouse){this.houseSession = {};this.houseSession.rooms = [];}
		
		for(var i in roomStyles) {
			if(!loadHouse){
			var roomSession = {
				roomId : Number(roomStyles[i].roomId),
				roomType : Number(roomStyles[i].roomType),
				position : {
					x : Number(roomStyles[i].structure[0].x),
					z : Number(roomStyles[i].structure[0].z)
				},
				size : {
					width : Number(roomStyles[i].structure[0].width),
					depth : Number(roomStyles[i].structure[0].depth)
				},
				facilities : []
			};
			this.houseSession.rooms.push(roomSession);
			this.houseSession.hsid = id;
			}
			for(var v in roomStyles[i].structure){
				var s=roomStyles[i].structure[v];
				var height=0;
				var mat=null;
				if(s.type=='floor'||s.type=='ceiling'){
					mat= new THREE.MeshBasicMaterial({color : 0x444444});
					height=10;
				} 
				else {
					mat= new THREE.MeshBasicMaterial({color : 0x556677});
					height=this.wallHight;
				}
				
				var geo=new THREE.CubeGeometry(parseInt(s.width),parseInt(height),parseInt(s.depth));
				if(s.type!='bwall'){
				var mesh=this.addMesh(geo, 1, parseInt(s.x), parseInt(s.y), parseInt(s.z), 0, 0, 0, mat, "wall", s.type);
				var texturePainting = THREE.ImageUtils.loadTexture("thumbs/imac.jpg", THREE.UVMapping);
				var tmpMat = new THREE.MeshLambertMaterial({
					map : texturePainting
				});
				mesh.material = tmpMat;

				}


			}
		}

	};
	this.addMesh = function(geometry, scale, x, y, z, rx, ry, rz, material, type, description) {

		geometry.computeBoundingBox();
		mesh = new THREE.Mesh(geometry, material);
		mesh.scale.x = mesh.scale.y = mesh.scale.z = scale;
		mesh.position.x = x;
		mesh.position.y = y;
		mesh.position.z = z;
		mesh.rotation.x = rx;
		mesh.rotation.y = ry;
		mesh.rotation.z = rz;
		mesh.overdraw = true;
		mesh.doubleSided = false;
		mesh.type = type;
		mesh.size = geometry.boundingBox.max.subSelf(geometry.boundingBox.min);
		mesh.updateMatrix();
		var today = new Date();
		mesh.name = Math.ceil((today.getTime() * 9301 + 49297) % 233280 / 233280.0 * 511555)+Math.round(Math.random()*10000);
		mesh.goodsName = description;
		mesh.description = description;
		// this.goodsInfo={name:me.rndId,type:'fac',goodsName:goodsGeo.goodsName,description:goodsGeo.description};
		switch(description){
            case 'floor':
              mesh.parasitizedFace={name:description,positionX:x,positionY:y+mesh.size.y/2,positionZ:z,sizeX:mesh.size.x,sizeY:0,sizeZ:mesh.size.z};
              break;
            case 'ceiling':
              mesh.parasitizedFace={name:description,positionX:x,positionY:y-mesh.size.y/2,positionZ:z,sizeX:mesh.size.x,sizeY:0,sizeZ:mesh.size.z};
              break;
            case 'fwall':
              mesh.parasitizedFace={name:description,positionX:x,positionY:y,positionZ:z+mesh.size.z/2,sizeX:mesh.size.x,sizeY:mesh.size.y,sizeZ:0};
              break;
            case 'bwall':
              mesh.parasitizedFace={name:description,positionX:x,positionY:y,positionZ:z-mesh.size.z/2,sizeX:mesh.size.x,sizeY:mesh.size.y,sizeZ:0};
              break;          
            case 'lwall':
              mesh.parasitizedFace={name:description,positionX:x+mesh.size.x/2,positionY:y,positionZ:z,sizeX:0,sizeY:mesh.size.y,sizeZ:mesh.size.z};
              break;
            case 'rwall':
              mesh.parasitizedFace={name:description,positionX:x-mesh.size.x/2,positionY:y,positionZ:z,sizeX:0,sizeY:mesh.size.y,sizeZ:mesh.size.z};
              break; 
          }
		scene.add(mesh);
		// console.warn(mesh.name);
		return mesh;

	};
};
House.prototype = {
	constructor : House,

	load : function(modHouse) {
		// 		1,loadHouseStyle;
		// load:function(h,house,facility,scene){

		this.houseSession = {};
		me = this;
		// console.warn(modHouse);
		$.post(loadHouseUrl, {
			h : modHouse
		}, function(data) {
			console.warn(data);
			// me.houseSession._id=data._id.$id;
			// me.houseSession._id=data._id;
			me.houseSession=modHouse;
			me.loadHouseStyle(modHouse.hsid, data.roomStyles,true);
			faciStyle=data.faciStyle;
			for(i in faciStyle) {
			  /**
			   * 需要增加获得宿主信息。hostFacInfo
			   */
			  hostFacInfo={rndId:faciStyle[i].rndId,parasitizedFace:faciStyle[i].parasitizedFace};
				me.facility.load(faciStyle[i].gid, hostFacInfo,faciStyle[i].position);
				console.warn(me.facility.goodsInfo);
				me.facility.facMesh = null;
			}
		}, "json");
		// (goodsGeo,scene,goodsTyp,houseSession)
		// $.post(loadHouseUrl,{h:modHouse},
		// function(data){
		// console.warn(data);
		// },"json");

	},
	loadHouseStyle : this.loadHouseStyle,
	addFacility : function(goodsGeo, hostFacInfo) {
		this.facility.load(goodsGeo,hostFacInfo);
		this.houseGoodsInfo = this.facility.goodsInfo;

	},
	moveFacility : function(mouse2D) {
		this.facility.move(mouse2D);
		this.facilityMoveFlg = true;
	},
	
	 moveFacilityOnHost : function(mouse2D,host) {
    // this.facility.moveOn(mouse2D);
    this.facility.moveOnHost(mouse2D,host);
    this.facilityMoveFlg = true;
  },

	/**
	 * paintType 0,color;1,wall paper
	 */

	paintWall : function(cOrw, wallName, paintType) {

		if(wallName) {
			var wallMesh = this.scene.getChildByName(wallName);
			this.paintSingleWall(wallMesh, cOrw, paintType);
		} else {
			for(var c = 0, cl = this.scene.children.length; c < cl; c++) {
				var child = this.scene.children[c];
				if(child.type === 'wall') {
					this.paintSingleWall(child, cOrw, paintType);
				}
			}
		}

	},
	paintSingleWall : function(wallMesh, cOrw, paintType) {

		switch(paintType) {
			case 0:
				var xColor = cOrw.replace('#', '0x');
				wallMesh.material = new THREE.MeshLambertMaterial({
					color : xColor/*, opacity: 1, shading: THREE.FlatShading */
				});
				break;
			case 1:
				var texturePainting = THREE.ImageUtils.loadTexture("thumbs/" + cOrw, THREE.UVMapping);
				var tmpMat = new THREE.MeshLambertMaterial({
					color : 0xffffff,
					map : texturePainting
				});
				wallMesh.material = tmpMat;
				break;
		}

	},
	// /**
	//    * paintType 0,color;1,wall paper
	//    */
	//   paintWall:function(cOrw,paintType,wallName){
	//      if(wallName){
	//              var wallMesh=this.scene.getChildByName(wallName);
	//              this.paintSingleWall(wallMesh,cOrw,paintType);
	//
	//       }else{
	//           for ( var c = 0, cl = this.scene.children.length; c < cl; c ++ ) {
	//                  var child = this.scene.children[ c ];
	//                  if ( child.type === 'wall' ) {
	//                    this.paintSingleWall(child,cOrw,paintType);
	//                  }
	//                }
	//       }
	//
	//   },
	//

	releaseFacility : this.releaseFacility,
	getFacility : function(mouse2D, plane) {
	  
		if(this.facility.getOnBoard(mouse2D, plane, this.scene, this.camera)) {
			this.houseGoodsInfo = this.facility.goodsInfo;
			this.facility.goodsInfo = null;
			return true;
		} else {
			return false;
		}

	},
	save : function() {
		// alert(eval(this.houseSession[0].rooms));
		//$.post(saveHouseUrl,{house:eval(this.houseSession),houseId:this.hsid},
		console.warn(this.houseSession);
		$.post(saveHouseUrl, {
			hSession : this.houseSession
		}, function(data) {
			console.log(data);
			// $('body').html(data);
		}, "json");
	},
	clear : function() {
		// 		1,clearFacilites;
		// 		2,clearHouseStyles;
	},
	clearFacilities : function() {

	},
	showFacilities : function() {
		// for (i in goods){
		// alert(i);
		// }

		$.post(loadHouseUrl, {
			h : h
		}, function(data) {
			// // $('.house').html(data);
			// console.warn(data);
			house.loadHouseStyle(data.hs._id.$id, data.hs.roomStyles);
			for(i in data['gd']) {
        /**
         * 获得宿主信息hostFacInfo
         */
				facility.loadMesh(data['gd'][i], h['goods'][i]);
				facility.locate(event);
				var ihs = -1;

				this.houseSession.push({
					gid : facility.goods.gid,
					position : {
						x : facility.goods.position.x,
						y : facility.goods.position.y,
						z : facility.goods.position.z
					},
					rotation : {
						x : facility.goods.rotation.x,
						y : facility.goods.rotation.y,
						z : facility.goods.rotation.z
					}
				});
				console.warn(house.goods);
			}
			//objects.push(facMesh);
			facility.initCursor(scene, $('.stage canvas'));
			//scene.add(facMesh);

		}, "json");
	}
}